<?php

namespace app\manager\model;

use think\Model;
use Carbon\Carbon;
use app\common\traits\model\TraitModel;

class Calendar extends Model
{
    protected $table = 'user_caravan_calendar';

    use TraitModel;

    const CARAVAN_LOCK_STATUS = 1;
    const CARAVAN_SHARE_STATUS = 2;
    const CARAVAN_RENT_STATUS = 3;//出租状态
    const CARAVAN_SHARE_RENT_STATUS = 4;//分享出租状态
    const CARAVAN_PRIVATE_STATUS = 1;
    const CARAVAN_ORDER_STATUS = 11;

    protected static $caravan_status = [
        'private' => self::CARAVAN_PRIVATE_STATUS,
        'share' => self::CARAVAN_SHARE_STATUS,
        'rent' => self::CARAVAN_RENT_STATUS,
        'sharerent' => self::CARAVAN_SHARE_RENT_STATUS,
    ];
    /**
     * 初始化房车日历
     * @param  [type]  $caravan_id [description]
     * @param  integer $y          初始化年数
     * @return [type]              [description]
     */
    public function initCaravanCarlendar($caravan_id, $y = 1)
    {
        $camp_id = model('Caravans')->where('id',$caravan_id)->value('services');
        $travel_money_base = model('Camps')->where('id',$camp_id)->value('travel_money_base');
        $rent_money_base = model('Camps')->where('id',$camp_id)->value('rent_money_base');
        

        $diffday = Carbon::now()->addYear($y)->diffInDays(Carbon::now());
        
        if ($caravan_datetimes = $this->where('caravan_id', $caravan_id)->order('datetimes', 'desc')->value('datetimes')) {
            $diffday = Carbon::now()->addYear($y)->diffInDays(Carbon::createFromFormat('Y-n-j', $caravan_datetimes));
        }
        if ($diffday > 1) {
            $this->startTrans();
            try {
                for ($i=0; $i < $diffday; $i++) { 
                   $datetimes = Carbon::now()->addDay($i)->toDateString();

                   $xishu = $this->getCoefficient($datetimes);
                   $rent_money_base = $rent_money_base * $xishu;//单日价格*系数

                   $this->create(['caravan_id' => $caravan_id, 'datetimes' => $datetimes, 'travel_money_base' => $travel_money_base, 'single_day_price' => $rent_money_base]);
                }
                $this->commit();

            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
        }
        return true;
    }
    public function setWhere($query = [])
    {
        $start_date = $query['start_date'];
        $end_date = isset($query['end_date']) ? $query['end_date'] : '';
        

        if (!is_array($start_date)) {
            if (strpos($start_date, ',')) {
                $start_date = explode(',', $start_date);
            }else{
                $end_date = $end_date ? : $start_date;  
            }
        }
        unset($query['start_date'], $query['end_date']);

        if (is_array($start_date)) {
            $this->where('datetimes', 'in', $start_date);
        }else{
            $this->where('datetimes', 'between', [$start_date, $end_date]);
        }

        $this->where($query);

        return $this;
    }
    /**
     * 设置会员房车状态日
     * @param [type] $caravan_id [description]
     * @param [type] $userType   [description]
     * @param [type] $status     [description]
     * @param [type] $start_date [description]
     * @param [type] $end_date   [description]
     */
    private function setUserCaravanCarlendar($caravan_id, $update_info)
    {
    	$this->startTrans();
    	try {
    		$this->update($update_info);
    		//$this->refreshCaravanStatuDateLine($caravan_id);
    		$this->commit();
    	} catch (Exception $e) {
    		$this->rollback();
    		return false;
    	}
        return true;    	
    }
    /**
     * 设置用户房车分享时间段
     * @param [type]  $caravan_id [description]
     * @param boolean $userType   [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function setUserCaravanCarlendarIsShare($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['status' => self::CARAVAN_SHARE_STATUS]);
    } 
    /**
     * 设置用户房车锁定时间段
     * @param [type] $caravan_id [description]
     * @param [type] $userType   [description]
     * @param [type] $start_date [description]
     * @param string $end_date   [description]
     */
    public function setUserCaravanCarlendarIsLock($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['status' => self::CARAVAN_LOCK_STATUS]);
    }
    /**
     * 解除用户房车锁定
     * @param [type] $caravan_id [description]
     * @param [type] $start_date [description]
     * @param string $end_date   [description]
     */
    public function setUserCaravanCarlendarIsUnLock($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['status' => self::CARAVAN_LOCK_STATUS]);
    }

    /**
     * 设置用户房车出租时间段
     * @param [type]  $caravan_id [description]
     * @param boolean $userType   [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function setUserCaravanCarlendarIsRent($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['status' => self::CARAVAN_RENT_STATUS]);
    }

    /**
     * 设置用户房车分享出租时间段
     * @param [type]  $caravan_id [description]
     * @param boolean $userType   [description]
     * @param [type]  $start_date [description]
     * @param string  $end_date   [description]
     */
    public function setUserCaravanCarlendarIsSharerent($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['status' => self::CARAVAN_SHARE_RENT_STATUS]);
    }

    /**
     * 设置用户房车私有时间段
     * @param [type] $caravan_id [description]
     * @param [type] $start_date [description]
     * @param string $end_date   [description]
     */
    public function setUserCaravanCarlendarIsPrivate($caravan_id, $start_date, $end_date = '')
    {
        return $this->setWhere(compact('start_date','end_date','caravan_id'))
                    ->setUserCaravanCarlendar($caravan_id, ['status' => self::CARAVAN_PRIVATE_STATUS]);
    }
    /**
     * 刷新房车状态时间段
     * @param  [type] $caravan_id [description]
     * @return [type]             [description]
     */
    protected function refreshCaravanStatuDateLine($caravan_id)
    {
    	model('CarCalendar')->where('caravan_id', $caravan_id)->delete();
        $user_id = model('user/Users')->getUserId();
        $park_id = model('Cards')->where('caravans_id',$caravan_id)->value('park_id');
        $camp_id = model('Manager/Parks')->where('id',$park_id)->value('camp_id');
        $camp_name = model('Camps')->where('id',$camp_id)->value('name');
        $camp_address = model('Camps')->where('id',$camp_id)->value('address');
        $camp_area = model('Camps')->where('id',$camp_id)->value('area');
        $lat1 = model('Camps')->where('id',$camp_id)->value('lat');
        $lng1 = model('Camps')->where('id',$camp_id)->value('lng');
        foreach (self::$user_types as $t_k => $user_type) {
            foreach (self::$caravan_status as $status) {
                $dates = $this->where('user_id', '')->where('caravan_id', $caravan_id)->where('status', $status)->where('user_type', 'in', $user_type)->column('datetimes'); 
                if ($dates) {
                $d_ls = $this->combination($dates, false);
                    foreach ($d_ls as $value) {
                         model('CarCalendar')->create(['id' => $this->uuid(),'user_id' => $user_id, 'caravan_id' => $caravan_id, 'status' => $status, 'user_type' => $t_k,'camp_name' =>$camp_name,'camp_address' =>$camp_address,'lat' =>$lat1,'lng' =>$lng1, 's' => $value['start'],'area' =>$camp_area, 'e' => $value['end']]);
                    }
                }
            }
        }
    }
    /**
     * 生成订单同步修改房车状态
     * @param  [type] $caravan_id [description]
     * @param  [type] $user_id    [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function ordered($caravan_id, $user_id, $start_date, $end_date = '')
    {
        if ($use_user_caravn_id = model('Cards')->where('user_id', $user_id)->value('caravans_id')) {
            $this->setUserCaravanCarlendarIsShare($use_user_caravn_id, self::CARAVAN_SHARE_STATUS, $start_date, $end_date);
        }
        
        $update_info = ['user_id' => $user_id, 'status' => self::CARAVAN_ORDER_STATUS, 'is_lock' => self::CARAVAN_LOCK_STATUS];
        $is_lock = ['<>', 0];
        $status = self::CARAVAN_SHARE_STATUS;
        $this->setWhere(compact('start_date','end_date','caravan_id','is_lock','status'))
                    ->setUserCaravanCarlendar($caravan_id, $update_info);
    }
    /**
     * 取消订单同步修改房车状态
     * @param  [type] $caravan_id [description]
     * @param  [type] $user_id    [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function delordered($caravan_id, $user_id, $start_date, $end_date = '')
    {
        $update_info = ['user_id' => '', 'status' => self::SENIOR_USER, 'is_lock' => self::CARAVAN_LOCK_STATUS];

        $this->setWhere(compact('start_date','end_date','caravan_id','user_id'))
                    ->setUserCaravanCarlendar($caravan_id, $update_info);
    }
    public function sendSearchMsg()
    {
        SmsFactory::init('MailAliyun')->sendSearch('9714928@qq.com','有用户更新啦！');
    }
    /**
     * 校验用户分享时间段
     * @param  [type] $caravan_id [description]
     * @param  [type] $start_date [description]
     * @param  string $end_date   [description]
     * @return [type]             [description]
     */
    public function checkUserCaravanStatus($caravan_id, $start_date, $end_date = '')
    {
        $query = $this->where('caravan_id', $caravan_id);

        $end_date = $end_date ? : $start_date;
        $query = $query->where('datetimes', 'between', [$start_date, $end_date]);
        return $query->where('status', self::CARAVAN_PRIVATE_STATUS)->count() ? false : true;
    }
    /**
     * 获取房车状态数组
     * @param  [type] $caravan_id [description]
     * @return [type]             [description]
     */
    public function getCaravanStatus($caravan_id)
    {
        $rs = ['1' => [], '2' => [], '11' => []];

        if ($caravanCalendars = $this->where('caravan_id', $caravan_id)->select()) {
         // halt($caravanCalendars);  
            foreach ($caravanCalendars as $calendar) {
                if (empty($calendar->user_id)) {
                    $rs[$calendar->status][] = $calendar->datetimes;
                }else{
                    $rs['11'][] = $calendar->datetimes;
                }
            }
        }

        return $rs;
    }
    public function test($caravan_id, $status, $start_date, $end_date = '')
    {
    	for ($ii=0; $ii < 10; $ii++) { 
	    	$user_id = $this->uuid();
	    	$caravan_id = $this->uuid();

	    	for ($i=0; $i < 365; $i++) { 
	            $d = 41911 + $i;
	            model('Calendar')->create(['user_id'=>$user_id,'caravan_id'=>$caravan_id,'status'=>1,'datetimes'=>Carbon::minValue()->addDay($d)->toDateString()]);
	        }
	    }return;
	    $as = self::distinct(true)->field('user_id,caravan_id')->select();
	    //halt($as);
	    foreach ($as as $a) {
	    	// if (!is_array($start_date)) {
	    	// 	$end_date = $end_date ? : $start_date;
	    	// 	$query = $query->where('datetimes', 'between', [$start_date, $end_date]);
	    	// }else{
	    	// 	$query = $query->where('datetimes', 'in', $start_date);
	    	// }
	    	// $query->update(['status'=>$status]);

	    	$dates = $this->where('user_id', $a->user_id)->where('status', 2)->column('datetimes');
	    	if ($dates) {
	    		# code...
	    		$d_ls = $this->combination($dates, false);
		        foreach ($d_ls as $value) {
		            model('CarCalendar')->create(['user_id'=>$a->user_id,'caravan_id'=>$a->caravan_id,'status'=>2,'s'=>$value['start'],'e'=>$value['end']]);
		        }
	    	}
	        
	    }

    	// $query = $this->where('user_id', '58d517ce-ac7b-48fe-aa50-894c6d9abdf3');
    	// // if (!is_array($start_date)) {
    	// // 	$end_date = $end_date ? : $start_date;
    	// // 	$query = $query->where('datetimes', 'between', [$start_date, $end_date]);
    	// // }else{
    	// // 	$query = $query->where('datetimes', 'in', $start_date);
    	// // }
    	// // $query->update(['status'=>$status]);

    	// $dates = $query->where('status', 2)->column('datetimes');
     //    //dump($this->combination($dates, false));
     //    $d_ls = $this->combination($dates, false);
     //    foreach ($d_ls as $key => $value) {
     //        model('CarCalendar')->create(['user_id'=>'58d517ce-ac7b-48fe-aa50-894c6d9abdf3','caravan_id'=>'21630711-a26e-42aa-82b7-fc7c65802e7e','status'=>2,'s'=>$value['start'],'e'=>$value['end']]);
     //    }
    	return;
    	
    }
}
